package com.yuzhihao.writejvm.clazz;

import com.yuzhihao.writejvm.constant.ConstantClassInfo;
import com.yuzhihao.writejvm.format.PrintFormat;
import com.yuzhihao.writejvm.read.Parse;
import lombok.Data;
import lombok.extern.log4j.Log4j2;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.Objects;

/**
 *
 * The this_class
 *
 * @author yzh
 * @since  2021年12月09日14:22:16
 */

@Data
@Log4j2
public class ThisClass implements Parse{

    private int index_u2 = 2;

    private int index;

    private String access;

    private String clazz;

    private String intfac;

    @Override
    public void parse(DataInputStream dis, ClassInfo ci) {
        try {
            this.index = Parse.byteToInt(index_u2, dis);
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        this.out(ci);
    }

    public void out(ClassInfo ci) {
        ConstantClassInfo cp = (ConstantClassInfo)ci.getCp_info().getPools().get(String.valueOf(index));

        this.access = ci.getAccess_flags().access();

        this.clazz = cp.getConstant();

        ci.setThis_class(this);
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();

        if(Objects.nonNull(this.access)){
            builder.append(this.access).append(PrintFormat.EMPTY);
        }
        builder.append("class")
                .append(PrintFormat.EMPTY)
                .append(this.clazz);

        if(Objects.nonNull(this.intfac)){
            builder.append(this.intfac);
        }
        builder.append(System.lineSeparator());

        return builder.toString();
    }

}
